package com.dqhl.business.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dqhl.business.Base.BaseActivity;
import com.dqhl.business.R;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Constant;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.CouponUseConditionPopupWindow;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description: 添加优惠券
 * autour: guanluocang
 * date: 2016/11/7 17:21
 */
public class AddCouponActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_goodsGoBack;
    private TextView tv_goodsTopTitle;
    private TextView tv_couponUse;//使用条件
    private LinearLayout ll_manjian;//满减
    private LinearLayout ll_discount;//折扣
    private LinearLayout ll_cash;//现金券
    private EditText et_manjianOne;//满100 减 50
    private EditText et_manjianTwo;
    private EditText et_discountCount;//1折
    private EditText et_cashCount;//10元 现金券
    private TextView tv_couponCount;//优惠券张数
    private TextView tv_endTime;
    private TextView tv_startTime;
    private CouponUseConditionPopupWindow mCouponUseConditionPopupWindow;
    //时间选择器
//    TimePickerDialog mDialogMonthDayHourMinute;
    TimePickerDialog mDialogAll;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

    private TextView tv_cancel;
    private TextView tv_save;
    private String condition; //使用条件 1.满减 2.折扣 3现金
    private String startTime;
    private String stopTime;
    private String denomination; //优惠券面值
    private String deno; //减免值 满减时传
    private String limited; //每人限发

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_coupon);
        initView();
        initData();
        TimePicker();
    }

    private void initView() {
        ll_manjian = (LinearLayout) findViewById(R.id.ll_manjian);
        ll_discount = (LinearLayout) findViewById(R.id.ll_discount);
        ll_cash = (LinearLayout) findViewById(R.id.ll_cash);
        tv_couponUse = (TextView) findViewById(R.id.tv_couponUse);
        tv_startTime = (TextView) findViewById(R.id.tv_startTime);
        tv_endTime = (TextView) findViewById(R.id.tv_endTime);
        et_manjianOne = (EditText) findViewById(R.id.et_manjianOne);
        et_manjianTwo = (EditText) findViewById(R.id.et_manjianTwo);
        iv_goodsGoBack = (ImageView) findViewById(R.id.iv_goodsGoBack);
        tv_goodsTopTitle = (TextView) findViewById(R.id.tv_goodsTopTitle);
        tv_goodsTopTitle.setText("添加优惠券");
        tv_couponCount = (TextView) findViewById(R.id.tv_couponCount);
        ll_manjian = (LinearLayout) findViewById(R.id.ll_manjian);
        ll_discount = (LinearLayout) findViewById(R.id.ll_discount);
        ll_cash = (LinearLayout) findViewById(R.id.ll_cash);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        tv_save = (TextView) findViewById(R.id.tv_save);
        et_discountCount = (EditText) findViewById(R.id.et_discountCount);
        et_cashCount = (EditText) findViewById(R.id.et_cashCount);

        tv_save.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        iv_goodsGoBack.setOnClickListener(this);
        tv_couponUse.setOnClickListener(this);
        tv_startTime.setOnClickListener(this);
        tv_endTime.setOnClickListener(this);
        tv_couponCount.setOnClickListener(this);
    }

    private void initData() {
        condition = "1";
        startTime = "";
        stopTime = "";
        limited = "1";
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_goodsGoBack:
                finish();
                break;
            //使用条件
            case R.id.tv_couponUse:
                showStatusPopWindow();
                break;
            //起始时间
            case R.id.tv_startTime:
                showStartTimeDialog();
                break;
            //截止时间
            case R.id.tv_endTime:
                showStopTimeDialog();
                break;
            //派发权限
            case R.id.tv_couponCount:
                couponCountPopWindow();
                break;
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_save:
                doSaveCoupon();
                break;
        }
    }

    private void showStartTimeDialog() {
        TimePickerDialog startDialog = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        long nowTime = System.currentTimeMillis();
                        if (nowTime < millseconds) {
                            startTime = text;
                            tv_startTime.setText(text);
                        } else {
                            toast("请大于当前日期");
                        }
                    }
                })
                .build();
        startDialog.show(getSupportFragmentManager(), "month_day_hour");
    }

    private void showStopTimeDialog() {
        TimePickerDialog stopDialog = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        long nowTime = System.currentTimeMillis();
                        if (nowTime < millseconds) {
                            stopTime = text;
                            tv_endTime.setText(text);
                        } else {
                            toast("请大于当前日期");
                        }
                    }
                })
                .build();
        stopDialog.show(getSupportFragmentManager(), "month_day_hour");
    }

    /**
     * 保存提交
     */
    private void doSaveCoupon() {
        if ("1".equals(condition)) {
            denomination = et_manjianOne.getText().toString().trim();
            deno = et_manjianTwo.getText().toString().trim();
        } else if ("2".equals(condition)) {
            denomination = et_discountCount.getText().toString().trim();
            deno = "";
        } else if ("3".equals(condition)) {
            denomination = et_cashCount.getText().toString().trim();
            deno = "";
        }
        if (TextUtils.isEmpty(denomination)) {
            toast("请填写优惠值");
        } else if (TextUtils.isEmpty(startTime)) {
            toast("请选择起始时间");
        } else if (TextUtils.isEmpty(stopTime)) {
            toast("请选择截止时间");
        } else {
            Dlog.e(user.getUser_id() + ";" + condition + ";" + denomination + ";" + deno
                    + ";" + startTime + ";" + stopTime + ";" + limited);
            showCustomLoadBar(".");
            RequestParams params = new RequestParams(Config.personal_coupon_add);
            params.addBodyParameter("seller_id", user.getUser_id());
            params.addBodyParameter("condition", condition);
            params.addBodyParameter("denomination", denomination);
            params.addBodyParameter("deno", deno);
            params.addBodyParameter("start_time", startTime);
            params.addBodyParameter("end_time", stopTime);
            params.addBodyParameter("limited", limited);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    String errMsg = JsonUtils.getErrMsg(result);
                    if (0 == errCode) {
                        sendAddSuccessBroadcast();
                        finish();
                    }
                    toast(errMsg);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    private void sendAddSuccessBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_ADD_COUPON);
        sendBroadcast(intent);
    }


    //使用条件popwindow
    private void showStatusPopWindow() {

        final List<String> useConditionList = new ArrayList<>();
        useConditionList.add("满减");
        useConditionList.add("折扣");
        useConditionList.add("优惠");
        mCouponUseConditionPopupWindow = new CouponUseConditionPopupWindow(AddCouponActivity.this, useConditionList,
                new CouponUseConditionPopupWindow.IOnItemSelectListener() {
                    @Override
                    public void onItemClick(int position) {
                        if (position == 0) {
                            condition = "1";
                            ll_manjian.setVisibility(View.VISIBLE);
                            ll_discount.setVisibility(View.GONE);
                            ll_cash.setVisibility(View.GONE);
                        } else if (position == 1) {
                            condition = "2";
                            ll_manjian.setVisibility(View.GONE);
                            ll_discount.setVisibility(View.VISIBLE);
                            ll_cash.setVisibility(View.GONE);
                        } else {
                            condition = "3";
                            ll_manjian.setVisibility(View.GONE);
                            ll_discount.setVisibility(View.GONE);
                            ll_cash.setVisibility(View.VISIBLE);
                        }
                        tv_couponUse.setText(useConditionList.get(position));
                    }
                });
        mCouponUseConditionPopupWindow.setWidth(tv_couponUse.getWidth());
        mCouponUseConditionPopupWindow.showAsDropDown(tv_couponUse);
    }

    //派发权限popwindow
    private void couponCountPopWindow() {

        final List<String> couponCount = new ArrayList<>();
        couponCount.add("1");
        couponCount.add("2");
        couponCount.add("3");
        couponCount.add("4");
        couponCount.add("5");
        couponCount.add("无限");
        mCouponUseConditionPopupWindow = new CouponUseConditionPopupWindow(AddCouponActivity.this, couponCount,
                new CouponUseConditionPopupWindow.IOnItemSelectListener() {
                    @Override
                    public void onItemClick(int position) {
                        switch (position) {
                            case 0:
                                limited = "1";
                                break;
                            case 1:
                                limited = "2";
                                break;
                            case 2:
                                limited = "3";
                                break;
                            case 3:
                                limited = "4";
                                break;
                            case 4:
                                limited = "5";
                                break;
                            case 5:
                                limited = "不";
                                break;
                        }
                        tv_couponCount.setText(couponCount.get(position));
                    }
                });
        mCouponUseConditionPopupWindow.setWidth(tv_couponCount.getWidth());
        mCouponUseConditionPopupWindow.showAsDropDown(tv_couponCount);
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    //时间选择器
    public void TimePicker() {
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAll = new com.jzxiang.pickerview.TimePickerDialog.Builder()
                .setCancelStringId("Cancel")
                .setSureStringId("Sure")
                .setTitleStringId("TimePicker")
                .setYearText("Year")
                .setMonthText("Month")
                .setDayText("Day")
                .setHourText("Hour")
                .setMinuteText("Minute")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
                .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(12)
                .build();
    }
}
